﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using FgoDataCrawler.Entity;
using FgoDataCrawler.Message.FgoWiki;
using FgoDataCrawler.Utility;
using Newtonsoft.Json;
using NLog;

namespace FgoDataCrawler.Crawler
{
    public class FgowikiCrawler
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private const string BASE_URL = "https://fgowiki.com/";
        private const int SERVANT_AMOUNT = 205;
        private const string DEFAULT_CACHE_DIR = "D:\\temp\\FgoWiki";

        private CachedHttpClient chClient { get; set; }

        public FgowikiCrawler()
        {
            chClient = new CachedHttpClient(DEFAULT_CACHE_DIR);
        }

        public List<ServantInfo> FetchServants()
        {
            List<ServantInfo> servantInfos = new List<ServantInfo>();
            for (int id = 1; id <= SERVANT_AMOUNT; id++)
            {
                ServantInfo si = FetchServantById(id);
                servantInfos.Add(si);
            }
            return servantInfos;
        }

        public ServantInfo FetchServantById(int id)
        {
            string feature = "var datadetail = ";

            DateTime startTime;
            TimeSpan timeCost;
            string url = "https://fgowiki.com/guide/petdetail/" + id;
            logger.Info("开始抓取{0}", url);
            startTime = DateTime.Now;
            var content = chClient.GetAsString(id + ".html", url, Encoding.UTF8);
            timeCost = DateTime.Now - startTime;
            logger.Info("抓取完成，耗时{0}ms", timeCost.Milliseconds);

            var indexStart = content.IndexOf(feature) + feature.Length;
            var indexEnd = content.IndexOf("\n", indexStart);
            var length = indexEnd - indexStart - 1;
            var json = content.Substring(indexStart, length);

            var servantMsgList = JsonConvert.DeserializeObject<List<Servant>>(json);
            
            if (servantMsgList.Count > 0)
            {
                var servantMsg = servantMsgList[0];
                // ServantInfo si = new ServantInfo();
                // si.Id = servantMsg.ID;  // Int32.Parse(servantMsg.ID);
                // si.ChineseName = servantMsg.NAME;
                // si.JapaneseName = servantMsg.NAME_JP;
                // si.EnglishName = servantMsg.NAME_EN;

                // 一些修正
                if (servantMsg.ID == 158)
                {
                    servantMsg.NAME_EN = "Hessian Lobo";
                }
                servantMsg.Attributes = servantMsg.Attributes.Replace("·", "・");

                return servantMsg.ToServiceInfo();
            }
            return null;
        }
    }
}
